<?php
// SomeryC, a webcomic script by Zachary Weston Lewis
// Based on Somery by Robin de Graaf
// Copyright 2005-2006
// SomeryC is distributed under the Artistic License (see LICENSE.txt)
//
// ADMIN/SYSTEM/FUNCTIONS.PHP > 31-08-2007

// execute some stuff
extract($_POST);
extract($_GET);
mysql_connect($sqlhost, $sqluser, $sqlpass);
mysql_select_db($sqldb);
skinset();
loaduser();
$localver = "0.2.5";

// functions for the admin system, gathering data
function format_date($raw_date, $format="m.d.Y",$tz) {
	ereg("(....)-(..)-(..) (..):(..):(..)",$raw_date,$reg);
	return date($format, mktime($reg[4],$reg[5],$reg[6],$reg[2],$reg[3],$reg[1])+($tz*3600));
}

function skinset() {
	global $prefix, $skindir;
	$result = mysql_query("SELECT * FROM ".$prefix."settings");
	while($row=mysql_fetch_object($result)) {
		$skindir = $row->skindir;
	}
	$skindir = "skins/".$skindir;
	return;
}

function loadsettings() {
	global $prefix, $settings;
	$result = mysql_query("SELECT * FROM ".$prefix."settings");
	while($row=mysql_fetch_object($result)) {
		$settings['setskin'] = $row->skindir;
		$settings['startlevel'] = $row->startlevel;
		$settings['gmt'] = $row->gmt;
		$settings['startstatus'] = $row->startstatus;
		$settings['registration'] = $row->registration;
		$settings['comments'] = $row->comments;
		$settings['noposts'] = $row->noposts;
		$settings['archive'] = $row->archive;
		$settings['more'] = $row->more;
		$settings['nocomments'] = $row->nocomments;
	}
	return;
}

function loaduser($username="") {
	global $userdata, $prefix;
	if ($username) {
		$result = mysql_query("SELECT * FROM ".$prefix."users WHERE username = '$username'");
		while($row=mysql_fetch_object($result)) {
			$userdata['username'] = $row->username;
			$userdata['password'] = $row->password;
			$userdata['level'] = $row->level;
		}
	}
	return;
}

function loadprofile($username="",$profile) {
	global $prefix;
	if ($username && $profile) {
		$result = mysql_query("SELECT $profile FROM ".$prefix."profile WHERE username = '$username'");
		while($row=mysql_fetch_object($result)) {
			$text = $row->$profile;
		}
	}
	return $text;
}

// functions for the skin system
function menu() {
	global $checkauth,$prefix,$userdata;
	if ($checkauth) {
		echo "<a href='index.php'>index</a> ";
		echo "<a href='profile.php'>profile</a> ";
		if ($userdata['level'] >= 1) echo "<a href='comics.php'>comics</a> ";
		echo "<a href='team.php'>team</a> ";
		if ($userdata['level'] >= 3) echo "<a href='settings.php'>settings</a> ";
		if ($userdata['level'] >= 2) echo "<a href='chapters.php'>chapters</a> ";
		echo "<a href='login.php?a=logout'>logout</a> ";
	} elseif (!$checkauth) {
		$result = mysql_query("SELECT * FROM ".$prefix."settings");
		while($row=mysql_fetch_object($result)) {
			$settings['registration'] = $row->registration;
		}
		if ($settings['registration'] == 0) echo "you're not logged in";
		if ($settings['registration'] == 1) echo "<a href='register.php'>register</a>";
	}
}

// functions for formatting
function revertTimestamp($timestamp)
    {
    global $settings;
	//convert MySQL timestamp to UNIX timestamp
    $year=substr($timestamp,0,4);
    $month=substr($timestamp,5,2);
    $day=substr($timestamp,8,2);
    $hour=substr($timestamp,11,2);
    $minute=substr($timestamp,14,2);
    $second=substr($timestamp,17,2);
    //modify time according to GMT setting
    $hour += $settings['gmt'];
    //output date
    $newdate=mktime($hour,$minute,$second,$month,$day,$year);
    RETURN ($newdate);
}

function debbcode($text) {
	$text = ereg_replace("\[b\]|\[/b\]|\[i\]|\[/i\]|\[u\]|\[/u\]|\[img\]|\[/img\]|\[quote\]|\[/quote\]|\[email\]|\[/email\]|\[url\]|\[/url\]","", $text);
	return $text;
}

function bbcode($text,$type=0) {
	$text = ereg_replace("\r\r", "</p><p>", $text);
	$text = ereg_replace("\r\n\r\n", "</p><p>", $text);
	$text = ereg_replace("\n\n", "</p><p>", $text);
	$text = ereg_replace("\n", "<br />", $text);
	$text = preg_replace("/\[quote\](.+?)\[\/quote\]/is", "<blockquote><b>Quote:</b><br />\\1</blockquote>", $text);
	$text = preg_replace("/\[center\](.+?)\[\/center\]/is", "</p><center>\\1</center><p>", $text);
	$text = preg_replace("/\[b\](.+?)\[\/b\]/is", "<b>\\1</b>", $text);
	$text = preg_replace("/\[i\](.+?)\[\/i\]/is", "<i>\\1</i>", $text);
	$text = preg_replace("/\[u\](.+?)\[\/u\]/is", "<u>\\1</u>", $text);
	if ($type != 1) $text = preg_replace("/\[img\](.+?)\[\/img\]{1}/is", "<img src='\\1' border='0' alt=''>", $text);
	$text = preg_replace("/\[email\](.+?)\[\/email\]{1}/is", "<a href='mailto:\\1'>\\1</a>", $text);
	$text = preg_replace("/\[url=([^<]+?)\](.+?)\[\/url\]{1}/is", "<a href='\\1' target='_blank'>\\2</a>", $text);
	$text = preg_replace("/\[url\](.+?)\[\/url\]{1}/is", "<a href='\\1' target='_blank'>\\1</a>", $text);
	return $text;
}

function cleanstring($text) {
	$text = ereg_replace("[\x27]","&#39;",trim($text));
	$text = ereg_replace("[\x22]","&quot;",trim($text));
	strip_tags($text);
	$text = ereg_replace(">","&gt;",$text);
	$text = ereg_replace("<","&lt;",$text);
	$text = preg_replace("[\x5c\]","",$text);
	return $text;
}

function datetime($dt) {
	global $dtr;
	if (strlen($dt) == 8) {
		$dtr['ye'] = substr($dt,0,4);
		$dtr['mo'] = substr($dt,4,2);
		$dtr['da'] = substr($dt,6,2);
	}
	if (strlen($dt) == 4) {
		$dtr['ho'] = substr($dt,0,2);
		$dtr['mi'] = substr($dt,2,2);
	}
	return $dtr;
}

//functions for site navigation
function firstPost($linkActiveText="First",$linkInactiveText="") {
//creates a link which takes the reader to the first post
	global $prefix,$row;
	// DETERMINE CURRENT COMIC ID
	$currentComicID = $row->id;
	// TURN NEXT LINK "OFF"
	$nextLinkActive = 0;
	// MYSQL QUERY
	$resultQuery = mysql_query("SELECT * FROM ".$prefix."comics");
	$totalComics = mysql_num_rows( $resultQuery );
	// BEGIN MOVEMENT THROUGH COMICS UNTIL A SUITABLE "NEXT COMIC" IS FOUND
	while ( $nextLinkActive == 0 && $tempRow = mysql_fetch_object( mysql_query("SELECT * FROM ".$prefix."comics WHERE id > '0' AND status = '1' ORDER BY id") ) )
	{
		if ( $tempRow->status != 0 )
		{
			$previousPage = $tempRow->id;
			$nextLinkActive = 1;
		}
	}
	// DETERMINE IF LINK IS ACTIVE
	if( $currentComicID == $previousPage )
	{
		echo $linkInactiveText;
	}
	else
	{
		echo "<a href='index.php?p=$previousPage'>$linkActiveText</a>";
	}
}

function previousPost($linkActiveText="Previous",$linkInactiveText="No Older") {
//creates a link which takes the reader to the previous post
	global $prefix,$row;
	// DETERMINE CURRENT COMIC ID
	$currentComicID = $row->id;
	// TURN NEXT LINK "OFF"
	$nextLinkActive = 0;
	// MYSQL QUERY
	$resultQuery = mysql_query("SELECT * FROM ".$prefix."comics");
	$totalComics = mysql_num_rows( $resultQuery );
	// BEGIN MOVEMENT THROUGH COMICS UNTIL A SUITABLE "NEXT COMIC" IS FOUND
	while ( $nextLinkActive == 0 && $tempRow = mysql_fetch_object( mysql_query("SELECT * FROM ".$prefix."comics WHERE id < '".$currentComicID."' AND status = '1' ORDER BY id DESC") ) )
	{
		if ( $tempRow->status != 0 )
		{
			$previousPage = $tempRow->id;
			$nextLinkActive = 1;
		}
	}
	// DETERMINE IF LINK IS ACTIVE
	if( $nextLinkActive == 0 )
	{
		echo $linkInactiveText;
	}
	else
	{
		echo "<a href='index.php?p=$previousPage'>$linkActiveText</a>";
	}
}

function nextPost($linkActiveText="Next",$linkInactiveText="No Newer") {
//creates a link which takes the reader to the next post
	global $prefix,$row;
	// DETERMINE CURRENT COMIC ID
	$currentComicID = $row->id;
	// TURN NEXT LINK "OFF"
	$nextLinkActive = 0;
	// MYSQL QUERY
	$resultQuery = mysql_query("SELECT * FROM ".$prefix."comics");
	$totalComics = mysql_num_rows( $resultQuery );
	// BEGIN MOVEMENT THROUGH COMICS UNTIL A SUITABLE "NEXT COMIC" IS FOUND
	while ( $nextLinkActive == 0 && $tempRow = mysql_fetch_object( mysql_query("SELECT * FROM ".$prefix."comics WHERE id > '".$currentComicID."' AND status = '1' ORDER BY id") ) )
	{
		if ( $tempRow->status != 0 )
		{
			$nextPage = $tempRow->id;
			$nextLinkActive = 1;
		}
	}
	// DETERMINE IF LINK IS ACTIVE
	if( $nextLinkActive == 0 )
	{
		echo $linkInactiveText;
	}
	else
	{
		echo "<a href='index.php?p=$nextPage'>$linkActiveText</a>";
	}
}

function lastPost($linkActiveText="Last",$linkInactiveText="") {
//creates a link which takes the reader to the most recent post
	global $prefix,$row;
	// DETERMINE CURRENT COMIC ID
	$currentComicID = $row->id;
	// TURN NEXT LINK "OFF"
	$nextLinkActive = 0;
	// MYSQL QUERY
	$resultQuery = mysql_query("SELECT * FROM ".$prefix."comics");
	$totalComics = mysql_num_rows( $resultQuery );
	// BEGIN MOVEMENT THROUGH COMICS UNTIL A SUITABLE "NEXT COMIC" IS FOUND
	while ( $nextLinkActive == 0 && $tempRow = mysql_fetch_object( mysql_query("SELECT * FROM ".$prefix."comics WHERE status = '1' ORDER BY id DESC") ) )
	{
		if ( $tempRow->status != 0 )
		{
			$nextPage = $tempRow->id;
			$nextLinkActive = 1;
		}
	}
	// DETERMINE IF LINK IS ACTIVE
	if( $currentComicID == $nextPage )
	{
		echo $linkInactiveText;
	}
	else
	{
		echo "<a href='index.php'>$linkActiveText</a>";
	}
}

function dropArchive($title="---Archive---", $output="%",$type="title",$dtype="d/m/Y") {
//creates a drop-down menu containing all the comics
	global $total,$arow,$prefix,$p,$settings,$PHP_SELF;
	if ($settings['archive'] != "0") { $limit = " LIMIT ".$settings['archive']; }
	echo "<script type='text/javascript'>
		<!--
	   	function gotoSite(obj) {
			var s;
          		s=obj.options[obj.selectedIndex].value
         		location.href=s;
		}
		// -->
		</script>
		<select name='Archive' size='1' onchange='gotoSite(this)'><option value='index.php'>".$title."</option><option></option>";
		$result = mysql_query("SELECT * FROM ".$prefix."comics WHERE status = '1' ORDER BY id DESC$limit");
		while($row=mysql_fetch_object($result)) {
			echo "<option value='".$PHP_SELF."?p=".$row->id."'>".debbcode($row->title)."</option>";
			$info=eregi_replace("\%",$more,$output);
			echo $info;
		}
	echo "</select>";
}

function randomComicLink($text="Random Comic")
// Creates a link that points to a random, visible comic.
{
	global $total,$arow,$prefix,$p,$settings,$PHP_SELF;
	$comicOkay = 0;
	$checkQuery = mysql_query("SELECT * FROM ".$prefix."comics WHERE status = '1' ORDER BY id DESC");
	$totalComics = mysql_num_rows($checkQuery);
	$tempRow = mysql_fetch_object( $checkQuery );
	$highestComicID = $tempRow->id;
	while ( $comicOkay == 0 )
	{
		$comicID = rand( 1, $highestComicID );
		$checkQuery = mysql_query("SELECT * FROM ".$prefix."comics WHERE id = '".$comicID."' AND status = '1'");
		$tempRow = mysql_fetch_object( $checkQuery );
		if ( $tempRow->id ) { $comicOkay = 1; }
	}
	echo "<a href=\"$PHPSELF/index.php?p=$comicID\" alt=\"$text\">$text</a>";
}

function nextChapter($linkActiveText="Next Chapter",$linkInactiveText="")
// Creates a link that points to the first comic of the next chapter.
{
	global $prefix, $p, $row;
	// Determine what chapter the current comic is in.
	$currentChapter = $row->chapter;
	// Determine what the next chapter is.
	// What is the highest chapter id value?
	$check_query = "SELECT * FROM ".$prefix."chapters ORDER BY cid DESC";
	$temp_row = mysql_fetch_object(mysql_query($check_query));
	$highestChapter = $temp_row->cid;
	if ($currentChapter == $highestChapter)
	// There are no newer chapters.
	{
		echo $linkInactiveText;
	}
	else
	// There may be newer chapters.
	{
		do
		{
			// Increase chapter value.
			++$currentChapter;
			$check_query = "SELECT * FROM ".$prefix."comics WHERE chapter = '".$currentChapter."' AND status = '1' ORDER BY id";
			$chapterCount = mysql_num_rows(mysql_query($check_query));
		}
		while ($chapterCount <= 0 && $currentChapter < $highestChapter);
		if ($chapterCount <= 0)
		// There are no newer chapters with content.
		{
			echo $linkInactiveText;
		}
		else
		// There are newer chapters with content.
		{
			$temp_row = mysql_fetch_object(mysql_query($check_query));
			$comicID = $temp_row->id;
			echo "<a href='index.php?p=$comicID'>$linkActiveText</a>";
		}
	}
}

function previousChapter($linkActiveText="Previous Chapter",$linkInactiveText="")
// Creates a link that points to the first comic of the previous chapter.
{
	global $prefix, $p, $row;
	// Determine what chapter the current comic is in.
	$currentChapter = $row->chapter;
	// Determine what the previous chapter is.
	$lowestChapter = 1;
	if ($currentChapter == $lowestChapter)
	// There are no older chapters.
	{
		echo $linkInactiveText;
	}
	else
	// There may be older chapters.
	{
		do
		{
			// Decrease chapter value.
			--$currentChapter;
			$check_query = "SELECT * FROM ".$prefix."comics WHERE chapter = '".$currentChapter."' AND status = '1' ORDER BY id";
			$chapterCount = mysql_num_rows(mysql_query($check_query));
		}
		while ($chapterCount <= 0 && $currentChapter > $highestChapter);
		if ($chapterCount <= 0)
		// There are no older chapters with content.
		{
			echo $linkInactiveText;
		}
		else
		// There are older chapters with content.
		{
			$temp_row = mysql_fetch_object(mysql_query($check_query));
			$comicID = $temp_row->id;
			echo "<a href='index.php?p=$comicID'>$linkActiveText</a>";
		}
	}
}

// functions for the output engine
function comic() {
//displays the current comic
	global $settings, $row, $prefix, $PHP_SELF;
	echo "<img class=\"comicImage\" alt=\"[Comic: $row->title]\" src=\"$row->url\" />"; }
function archive($output="%",$type="title",$dtype="d/m/Y") {
	global $total,$arow,$prefix,$p,$settings,$PHP_SELF;
	if ($settings['archive'] != "0") { $limit = " LIMIT ".$settings['archive']; }
	$result = mysql_query("SELECT * FROM ".$prefix."articles WHERE status = '1' ORDER BY aid DESC$limit");
	while($row=mysql_fetch_object($result)) {
		if ($type == "date") $more = "<a href='".$PHP_SELF."?p=".$row->aid."&c=1'>".strtolower(debbcode(date($dtype,strtotime($row->date))))."</a>";
		if ($type == "title") $more = "<a href='".$PHP_SELF."?p=".$row->aid."&c=1'>".strtolower(debbcode($row->title))."</a>";
		if ($type == "td") $more = "<a href='".$PHP_SELF."?p=".$row->aid."&c=1'>".strtolower(debbcode(date($dtype,strtotime($row->date))))." - ".strtolower(debbcode($row->title))."</a>";
		$info=eregi_replace("\%",$more,$output);
		echo $info;
	}
	if (!$result) echo "empty";
}

function prevnext($next="newer posts",$divider=" - ",$previous="older posts") {
	global $total,$arow,$prefix,$p,$settings,$PHP_SELF,$offset;
	if (!$offset) { $offset = 0; }
	$offsetnext = $offset - $settings['noposts'];
	$offsetprev = $offset + $settings['noposts'];
      if ($offsetnext < 0) {
		$next = "no newer posts";
	} else {
		$next = "<a href='index.php?offset=$offsetnext'>$next</a>";
	}
	$resultz = mysql_query("SELECT * FROM ".$prefix."articles WHERE status = '1'");
	$totalz = mysql_num_rows($resultz);
	$change = $totalz - $settings['noposts'];
	if ($offset >= $change) {
		$prev = "no older posts";
	} else {
		$prev = "<a href='index.php?offset=$offsetprev'>$previous</a>";
	}
	echo $next.$divider.$prev;
}

function getauthor($item) {
	global $settings, $a_row, $prefix;
	$result2 = mysql_query("SELECT * FROM ".$prefix."profile WHERE username = '".$a_row->username."'");
	while($row2=mysql_fetch_object($result2)) {
		echo $row2->$item;
	}
}

function getcomicdate($dtype="%A, %d %B %Y") {
	global $dtr, $row, $prefix, $settings;
  $pubDate=strftime($dtype,revertTimestamp($row->time));
	echo $pubDate;
}

function getcomictime($dtype="%H:%M:%S") {
	global $dtr, $row, $prefix, $settings;
  $pubDate=strftime($dtype,revertTimestamp($row->time));
	echo $pubDate;
}

function getpostdate($dtype="%A, %d %B %Y") {
	global $dtr, $a_row, $prefix, $settings;
  $pubDate=strftime($dtype,revertTimestamp($a_row->time));
	echo $pubDate;
}

function getposttime($dtype="%H:%M:%S") {
	global $dtr, $a_row, $prefix, $settings;
  $pubDate=strftime($dtype,revertTimestamp($a_row->time));
	echo $pubDate;
}

function permalink() {
	global $settings, $a_row, $row, $prefix, $PHP_SELF;
	echo "$a_row->title";
}

function postBody() {
	global $settings, $a_row, $prefix, $p, $PHP_SELF;
	$body = cleanstring($a_row->body);
	$body = bbcode($body);
	echo $body;
}

function commentlink ($none="no comment",$single="1 comment",$more="% comments",$open="comment on this comic",$close="close") {
	global $row, $a_row, $prefix, $settings, $c, $a, $p, $PHP_SELF;
	echo"<a name='comments' />";
	if ($settings[comments] == 1 && $row->show_comments == 1) {
		$count = mysql_query("SELECT * FROM ".$prefix."comments WHERE parentid = $row->id");
		$total = mysql_num_rows($count);
		$t="$total";
		if ($total == 0) echo "<a class='comment' href=\"$PHP_SELF?p=$row->id&amp;c=1#comments\">$none</a>";
		else if ($total == 1) echo "<a class='comment' href=\"$PHP_SELF?p=$row->id&amp;c=1#comments\">$single</a>";
		else if ($total > 1) {
			$more=eregi_replace("\%",$t,$more);
			echo "<a class='comment' href=\"$PHP_SELF?p=$row->id&amp;c=1#comments\">$more</a>";
		}
		if($c!=0)
      echo " | <a href=\"$PHP_SELF?p=$row->id#comments\">$close</a>";
    elseif($c==0)
      echo" | <a href=\"$PHP_SELF?p=$row->id&amp;c=1#comments\">$open</a>";
	} else {
		echo $settings[nocomments];
	}
}

function getarticle($item) {
	global $settings, $row, $prefix;
	$result2 = mysql_query("SELECT * FROM ".$prefix."articles WHERE aid = '".$row->aid."'");
	while($row2=mysql_fetch_object($result2)) {
		echo $row2->$item;
	}
}

function getcomic($item) {
	global $settings, $row, $prefix;
	$result2 = mysql_query("SELECT * FROM ".$prefix."comics WHERE id = '".$row->id."'");
	while($row2=mysql_fetch_object($result2)) {
		echo $row2->$item;
	}
}

function getcomment($item) {
	global $settings, $c_row, $prefix, $dtr;
	$result2 = mysql_query("SELECT * FROM ".$prefix."comments WHERE coid = '".$c_row->coid."'");
	while($row2=mysql_fetch_object($result2)) {
		datetime($row2->time);
		if ($item == "date") {
		  $dtype = "%A, %d %B %Y";
  		$pubDate=strftime($dtype,revertTimestamp($row2->time));
			echo $pubDate;
		}
		if ($item == "time") {
		  $dtype = "%H:%M:%S";
  		$pubDate=strftime($dtype,revertTimestamp($row2->time));
			echo $pubDate;
		}
		if ($item != "date" && $item != "time") echo $row2->$item;
	}
}

function chapter () {
	global $row, $prefix;
	$result2 = mysql_query("SELECT * FROM ".$prefix."chapters WHERE cid = '".$row->chapter."'");
	while($row2=mysql_fetch_object($result2)) {
		echo $row2->chapter;
	}
}

function chapterlink () {
	global $row, $PHP_SELF;
	echo "$PHP_SELF?chapter=$row->chapter";
}

function userlink () {
	global $row, $PHP_SELF;
	echo "$PHP_SELF?user=$row->username";
}

function comment() {
	global $settings, $c_row, $prefix, $p;
	$result2 = mysql_query("SELECT * FROM ".$prefix."comments WHERE coid = '".$c_row->coid."'");
	while($row2=mysql_fetch_object($result2)) {
		$comment = cleanstring($row2->comment);
		$comment = bbcode($comment,1);
		echo $comment;
	}
}
?>
